package com.xudu.controller.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xudu.common.LogAnnotation;
import com.xudu.common.LogType;
import com.xudu.common.Result;
import com.xudu.controller.IUserController;
import com.xudu.entity.User;
import com.xudu.service.IUserService;
import com.xudu.utils.JWTUtil;
import com.xudu.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xudu
 * @since 2024-04-18
 */
@RestController
@RequestMapping("/user")
public class UserControllerImpl implements IUserController {

    @Autowired
    private IUserService iUserService;


    @LogAnnotation(operation = "用户",type = LogType.LOGIN)
    @Override
    public Result login(User user) throws Exception {
        if (iUserService.login(user)){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(User::getUsername,user.getUsername());
            User dbuser = iUserService.getOne(queryWrapper);

            //生成token
            String sign = JWTUtil.sign(user.getUsername());


            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(dbuser,userVo);

            //将token赋值给userVo 用于前端返回
            userVo.setToken(sign);

            return Result.success(userVo);

        }else {
            return Result.error("用户名或密码错误");
        }

    }

    @LogAnnotation(operation = "用户",type = LogType.REGISTER)
    @Override
    public Result register(User user) throws Exception {
        //判断是否为空

        //判断用户名是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername,user.getUsername());
        User dbuser = iUserService.getOne(queryWrapper);
        if(dbuser==null){
            boolean register = iUserService.register(user);
            if (register){
                return Result.success(user);
            }else {
                return Result.error("用户注册失败！");
            }

        }else {
            return Result.error("用户名重复！");
        }

    }
}
